#!/bin/bash 
###
 # @Descripttion: 
 # @Author: zheng xinyi
 # @Date: 2025-07-29 19:24:44
 # @LastEditors: zheng xinyi
 # @LastEditTime: 2025-07-30 23:42:33
### 
deploy_dist=1

db_server_user=root
db_server_ip=192.168.1.126

app_server_user=root
app_server_ip=192.168.1.126

workspace=`pwd`
network_name="external_net_1"  # 定义网络名称

# 创建外部网络函数
create_network() {
    local server_user=$1
    local server_ip=$2
    echo "检查服务器网络 $network_name..."
    
    # 检查网络是否已存在
    network_exists=$(ssh "docker network ls --format '{{.Name}}' | grep -w $network_name")
    
    if [ -z "$network_exists" ]; then
        echo "创建外部网络 $network_name..."
        ssh "docker network create $network_name"
        if [ $? -eq 0 ]; then
            echo "网络 $network_name 创建成功"
        else
            echo "网络创建失败"
            exit 1
        fi
    else
        echo "网络 $network_name 已存在"
    fi
}

case $1 in
   "app")
      if [[ "$dist_deploy" == '1' ]]; then 
         scp -r $workspace/app $app_server_user@$app_server_ip:~/ ;
         ssh $app_server_user@$app_server_ip "cd ~/app; ./app/deploy.sh $2 $3" ;
      else
         cd $workspace/app
         sudo ./deploy.sh $2 $3;
      fi ;;
   "db") 
      if [[ "$dist_deploy" == '1' ]]; then 
         scp -r $workspace/db $db_server_user@$db_server_ip:~/ ;
         ssh $db_server_user@$db_server_ip "cd ~/db; ./db/deploy.sh $2 $3" ;
      else
         cd $workspace/db
         sudo ./deploy.sh $2 $3;
      fi ;;
   "all") 
      if [[ "$dist_deploy" == '1' ]]; then 
         scp -r $workspace/db $db_server_user@$db_server_ip:~/ ;
         ssh $db_server_user@$db_server_ip "cd ~/app; ./db/deploy.sh $2 $3" ;

         scp -r $workspace/app $app_server_user@$app_server_ip:~/ ;
         ssh $app_server_user@$app_server_ip "cd ~/db; ./db/deploy.sh $2 $3" ;
      else
         cd $workspace/db
         sudo ./deploy.sh $2 $3;
         cd $workspace/app
         sudo ./deploy.sh $2 $3;
      fi ;;
   *)
   echo ""
   echo "命令使用方法： ./deploy.sh MODULE COMMAND [APPNAME]"
   echo ""
   echo "MODULE: "
   echo "   all 所有模块，包含app、db"
   echo "   app 业务应用模块"
   echo "   db 数据库模块"
   echo ""
   
   echo ""
   echo "COMMAND: "
   echo "   run 初始化配置并运行应用实例，配置文件修改后需要执行此命令，否则不生效。"
   echo "   start 启动应用实例。"
   echo "   stop 停止应用实例。"
   echo "   restart 重启应用实例。"
   echo "   remove 删除应用实例。"  
   echo "   destroy 删除应用实例和镜像。"
   echo "   package 打包当前模块的镜像，此操作一般为测试发包时使用。"
   echo "   load 加载镜像，此操作加载的镜像为 package 打包的结果。"
   echo "   package_update 打包更新应用镜像。更新包为./app/update/$deploy_module-images.tar 。"
   echo "   load_update 更新应用镜像，并重新启动应用示例。更新包为./app/update/$deploy_module-images.tar 。"

   echo ""
   echo "APPNAME: "
   echo "   xapi-xxx 后台服务api。名称格式：xapi代表后台服务，xxx代表模块的名称"
   echo "   xweb-xxx 前端web应用。名称格式：xweb代表前端应用，xxx代表应用系统的名称"
   echo "   xdb-xxx 数据库。名称格式：xdb代表数据库，xxx代表数据库服务名称。"
   echo ""
   exit 1  
esac 
